package com.fc.advbox.controller.open;

import com.fc.advbox.common.ResponseJson;
import com.fc.advbox.entity.PublicTokenEntity;
import com.fc.advbox.service.IPublicTokenService;
import com.fc.advbox.utils.R;
import com.fc.advbox.utils.RRException;
import com.fc.advbox.utils.StringUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

import static com.fc.advbox.utils.JsonUtils.sendJSON;

/**
 * Description:
 * User: Charles.Gao
 * Date: 2018-07-24 18:33
 */
@Configuration
public class OpenApiFilterConfigure {
    @Autowired
    private IPublicTokenService publicTokenService;

    @Bean
    public FilterRegistrationBean testFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new OpenApiFilter());//添加过滤器
        registration.addUrlPatterns("/api/open/*");//设置过滤路径，/*所有路径
//        registration.addInitParameter("name", "alue");//添加默认参数
        registration.setName("OpenApiFilter");//设置优先级
        registration.setOrder(1);//设置优先级
        return registration;
    }

    public class OpenApiFilter implements Filter {


        @Override
        public void destroy() {
        }

        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain
                filterChain)
                throws IOException, ServletException {
            HttpServletRequest req = (HttpServletRequest) request;

            String token = req.getHeader("access_token");
            Map<String, Object> params = new HashedMap();
            params.put("appId",req.getHeader("appid"));
            params.put("secret",req.getHeader("secret"));

            if(token == null || "".equals(token)){
                sendJSON((HttpServletResponse) response, ResponseJson.error(ResponseJson.UNAUTHRIZED, "令牌为空!请在header中传入access_token参数!"));
                return;
            }
            String tokenComputed = DigestUtils.md2Hex(StringUtils.createLinkString(params));

            PublicTokenEntity tokenEntity = publicTokenService.queryObject(params);
            if(tokenEntity == null){
                sendJSON((HttpServletResponse) response, ResponseJson.error(ResponseJson.UNAUTHRIZED, "无效的令牌!"));
                return;
            }
            if(!tokenComputed.equals(token)){
                sendJSON((HttpServletResponse) response, ResponseJson.error(ResponseJson.UNAUTHRIZED, "无效的令牌!"));
                return;
            }
            if(tokenEntity.getExpireTime().getTime()<new Date().getTime()){
                sendJSON((HttpServletResponse) response, ResponseJson.error(ResponseJson.TOKEN_TIMEOUT, "令牌失效，请重新获取!"));
                return;
            }

            filterChain.doFilter(request, response);
        }

        @Override
        public void init(FilterConfig arg0) throws ServletException {
        }
    }
}
